<template>
  <div class="app-container">
    <el-form :inline="true" ref="refForm" :model="form">
      <el-form-item label="查询时间" prop="time">
        <el-date-picker
          v-model="form.time"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="submitFilterForm">搜索</el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-download" @click="exportHandle">导出</el-button>
      <el-button @click="resetForm('refForm')">重置</el-button>
    </el-form>
    <el-table
      border
      :data="tableData"
      v-loading="loading"
      element-loading-text="加载中..."
      class="el-table-align-center">
      <el-table-column label="时间" prop="date" width="180" align="center">
      </el-table-column>
      <el-table-column prop="total" label="总登陆量" align="center"></el-table-column>
      <el-table-column prop="pc" label="PC端占比" align="center">
        <template slot-scope="{row}">
          {{row.pc}}%
        </template>
      </el-table-column>
      <el-table-column prop="ios" label="IOS占比" align="center">
        <template slot-scope="{row}">
          {{row.ios}}%
        </template>
      </el-table-column>
      <el-table-column prop="android" label="安卓占比" align="center">
        <template slot-scope="{row}">
          {{row.android}}%
        </template>
      </el-table-column>
      <el-table-column prop="h5" label="H5占比" align="center">
         <template slot-scope="{row}">
          {{row.h5}}%
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>


<script>
  import {getPlatformRateApi as listApi,exportPlatform} from "@/services/api/operational";
  import {grid} from '@/build'

  export default {
    name: "platform-rate",
    mixins: [grid],
    data() {
      // let times = _.toPeriod({
      //   start: [-1, 'days'],
      //   end: [0, 'days'],
      //   format: 'YYYY-MM-DD'
      // });
      // 本月时间本月1号至当前时间
      const monthTime = [moment().startOf('month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]

      return {
        tableData: [],
        form: {
          time: monthTime,
        },
        filters: {
          stime: moment(monthTime[0]).valueOf(),
          etime: moment(monthTime[1]).valueOf() +  86399999,
        },

      }
    },
    methods: {
      selfResetForm(formName) {
        this.resetForm(formName);
        this.submitFilterForm();
      },
      submitFilterForm() {
        const {time} = this.form;
        let stime = undefined, etime = undefined;
        if (!_.isUndefined(time) && _.isArray(time)) {
          stime = moment(time[0]).valueOf();
          etime = moment(time[1]).valueOf() +  86399999;
        }
        this.filters = {stime, etime, project: consts.PLATFROM_PREFIX}
        this.gridSearch()
      },
      getSummaries(param) {
        const {columns, data} = param;
        const sums = [];
        let length = _.keys(columns).length;

        columns.forEach((column, index) => {
          const values = data.map(item => Number(item[column.property]));
          if (index === 0) {
            sums[index] = '汇总';
            return;
          } else if ([1, 2, 3, 4, 5].indexOf(index) !== -1 && !values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = '';
          }
        });
        // sums[1] = _.formatDiv(sums[1],length);
        // sums[2] = _.formatDiv(sums[2],length,{fixed:2});
        // sums[3] = _.formatDiv(sums[3],length,{fixed:2});
        // sums[4] = _.formatDiv(sums[4],length,{fixed:2});
        // sums[5] = _.formatDiv(sums[5],length,{fixed:2});
        return sums;
      },
      //导出
      exportHandle() {
        let {stime, etime,page} = this.filters
        let ajaxData = {stime, etime,page}
        let filename = '操作端占比明细报表.csv';
        let header = ['时间', '总登陆量(已去量)', 'PC端占比', 'IOS占比','安卓占比','H5占比']
        let filterField = ['date', 'total', 'pc', 'ios','android','h5']
        exportPlatform(ajaxData).then(([result, data]) => {

if (result) {
            let exportData = this.responseFormatter(data);
            console.log(exportData)
            // return
            this.export2Excel(header, filterField, exportData, filename)

          } else {
            this.$message({message: '导出失败,' + data.message, type: "warning"})
          }
        })
      },
       responseFormatter(data) {
          let result = [];
          _.forIn(data, (value, key) => {
            let login = value.login || {};
            let visit = value.visit || {};
            let loginFake = {};//分别存各端数量
            let loginTotal = 0;//存总数
            _.each(login, (item) => {
              loginFake[item.name] = item.count;
              loginTotal += item.count;
            })
            let total = loginTotal ? loginTotal : 1;
            result.push({
              date: key,
              total: loginTotal,
              pc: _.formatDiv(loginFake['PC'], total, {fixed: 2}) + '%',
              ios: _.formatDiv(loginFake['IOS'], total, {fixed: 2}) + '%',//loginFake['IOS']/loginTotal,
              android: _.formatDiv(loginFake['安卓'], total, {fixed: 2}) + '%',//loginFake['安卓']/loginTotal,
              h5: _.formatDiv(loginFake['H5'], total, {fixed: 2}) + '%',//loginFake['H5']/loginTotal})
            })
          })

          result = _.sortBy(result, (item) => {
            return item.date;
          });
          return result.reverse();
      },
    },
    mounted() {

      this.bindGet(listApi, 'tableData', {
        action: 'getGrid',
        sendingData: 'filters',
        format: data => {
          let result = [];
          _.forIn(data, (value, key) => {
            let login = value.login || {};
            let visit = value.visit || {};
            let loginFake = {};//分别存各端数量
            let loginTotal = 0;//存总数
            _.each(login, (item) => {
              loginFake[item.name] = item.count;
              loginTotal += item.count;
            })
            let total = loginTotal ? loginTotal : 1;
            result.push({
              date: key,
              total: loginTotal,
              pc: _.formatDiv(loginFake['PC'], total, {fixed: 2}),
              ios: _.formatDiv(loginFake['IOS'], total, {fixed: 2}),//loginFake['IOS']/loginTotal,
              android: _.formatDiv(loginFake['安卓'], total, {fixed: 2}),//loginFake['安卓']/loginTotal,
              h5: _.formatDiv(loginFake['H5'], total, {fixed: 2}),//loginFake['H5']/loginTotal})
            })
          })

          result = _.sortBy(result, (item) => {
            return item.date;
          });
          return result.reverse();
        }
      });
      this.submitFilterForm();
    }

  }
</script>

<style scoped>

</style>
